<template>
	<a-drawer v-model:open="visible" ref="employeeDetailModalRef" class="edit-drawer modal-fixed-bottom"
		root-class-name="root-customer-drawer" width="800px" :closable="false" @close="onClose">
		<div class="closeable" @click="onClose">{{ $t('self.closeButton') }}</div>
		<div class="modal-header">{{ title }}</div>

		<a-form :model="formState" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol"
			@finish="onSubmit">
			<!-- 场站图 -->
			<a-form-item :label="$t('self.businessStation.tips9')">
				<a-upload name="file" v-model:file-list="uploadParams.pic1" :action="uploadParams.url" class="my-upload"
					:headers="uploadParams.header" :data="getUploadData" list-type="picture-card"
					:before-upload="makeBeforeUpload(1)" :show-upload-list="false" @change="handleUploadChange"
					@success="handleSuccess">
					<template #default>
						<div @click="uploadType = 1" style="width: 60px;text-align:center;padding-top:5px;">
							<img src="@/assets/homer.png" style="width: 50px;height: 50px;">
							<p style="color: #999;font-size: 12px;margin: 4px 0 0;">
								{{$t('self.businessStation.tips11')}}
							</p>
						</div>
					</template>
				</a-upload>
				<div class="upload-tip">
					<span>{{$t('self.businessStation.tips13')}}</span>
					<!-- <span class="count">{{ allAdv.length }}/5</span> -->
				</div>
				<div class="adv-list">
					<div v-for="(pics,idx) in allAdv" :key="idx" class="adv-item">
						<p class="pic-box">
							<img :src="pics.url" v-if="allAdv.length>0">
							<img v-else src="@/assets/homer.png">
						</p>
						<p class="del-box">
							<img @click="deletePileAdv(pics,1,idx)" src="@/assets/delete.png">
						</p>
					</div>
				</div>
			</a-form-item>


			<!-- 广告图 -->
			<a-form-item :label="$t('self.businessStation.tips10')">
				<a-upload name="file" v-model:file-list="uploadParams.pic2" :action="uploadParams.url"
					:headers="uploadParams.header" :data="getUploadData" list-type="picture-card" class="my-upload"
					:before-upload="makeBeforeUpload(2)" :show-upload-list="false" @change="handleUploadChange"
					@success="handleSuccess">
					<template #default>
						<div @click="uploadType = 2" style="width: 60px;text-align:center;padding-top:5px;">
							<img src="@/assets/homer.png" style="width: 50px;height: 50px;">
							<p style="color: #999;font-size: 12px;margin: 4px 0 0;">
								{{$t('self.businessStation.tips11')}}
							</p>
						</div>
					</template>
				</a-upload>
				<div class="upload-tip">
					<span>{{$t('self.businessStation.tips12')}}</span>
					<!-- <span class="count">{{ allAdv.length }}/5</span> -->
				</div>
				<div class="adv-list">
					<div v-for="(pics,idx) in allAdv2" :key="idx" class="adv-item">
						<p class="pic-box">
							<img :src="pics.url" v-if="allAdv2.length>0">
							<img v-else src="@/assets/homer.png">
						</p>
						<p class="del-box">
							<img @click="deletePileAdv(pics,2,idx)" src="@/assets/delete.png">
						</p>
					</div>
				</div>
			</a-form-item>
			<div class="base-flex base-rows base-align-items-center base-justify-content-center footer">
				<a-button type="primary" html-type="submit">{{ $t('self.submitButton') }}</a-button>
				<a-button class="base-ml10" @click="onClose">{{ $t('self.cancelButton') }}</a-button>
			</div>
		</a-form>
	</a-drawer>
</template>

<script setup>
	import {
		computed,
		getCurrentInstance,
		onMounted,
		ref
	} from 'vue'
	import {
		message
	} from 'ant-design-vue'
	import chooseAreaForLocal from '@/components/choose/choose-area-for-local.vue'
	import config from '@/config'
	const {
		proxy
	} = getCurrentInstance()
	const $TOOL = proxy.$TOOL
	const $API = proxy.$API
	const $T = proxy.$t
	import tool from '@/utils/tool'
	const emit = defineEmits(['close', 'ok'])
	const allAdv = ref([])
	const allAdv2 = ref([])
	const uploadType = ref(0) // 0 未选择  1 场站图  2 广告图
	const visible = ref(false)
	const token = tool.cookie.get(config.TOKEN_KEY);
	const uploadParams = ref({
		url: '',
		header: {

		},
		pic1: [], // 场站图片，多张
		pic2: [], // 广告图，多张
	})

	// 模式，add新增，show查看，edit编辑
	const mode = ref('add')
	const labelCol = {
		style: {
			width: '230px',
		},
	};
	const wrapperCol = {
		span: 16,
	};

	const title = ref('')
	const formState = ref({
		id: '',
		orgId: null,
	})
	onMounted(async () => {
		uploadParams.value.url = config.API_URL + '/admin/uploadStationImage'
		uploadParams.value.header.key = token
	})

	const handleUploadChange = (info) => {
		console.log('当前上传类型：', uploadType.value)
	}
	// 工厂函数：根据 type 生成闭包函数
	const makeBeforeUpload = (type) => () => {
		message.loading($T('self.businessStation.tips15'))
		uploadType.value = type
		if (allAdv.value.length >= 5 || allAdv2.value.length >= 5) {
			message.error($T('self.businessStation.tips14'))
			return false
		}
		return true
	}

	const onSubmit = (values) => {
		const params = {
			...formState.value
		}
		message.success($T('self.message.success'))
		onClose()
	}

	const getUploadData = () => {
		return {
			id: formState.value.id,
			type: uploadType.value
		}
	}
	const handleSuccess = (res, file) => {
		getPileAdv(uploadType.value)
	}
	const deletePileAdv = (item, type, index) => {
		const fileName = item.url.substring(item.url.lastIndexOf('/') + 1)
		$API.backend.businessStation.deleteStationImgs.post({
			id: item.id,
			fileName
		}).then(res => {
			if (res.code === 200) {
				type === 1 ?
					allAdv.value.splice(index, 1) :
					allAdv2.value.splice(index, 1)
			}
		})
	}

	const getPileAdv = async (type) => {
		if (!type) {
			const [sRes, aRes] = await Promise.all([
				$API.backend.businessStation.getStationImgs.post({
					id: formState.value.id,
					type: 1
				}),
				$API.backend.businessStation.getStationImgs.post({
					id: formState.value.id,
					type: 2
				})
			])
			// 后端可能返回 null / undefined / 空对象
			allAdv.value = (sRes.code === 200 && Array.isArray(sRes.objData?.[1])) ? sRes.objData[1].map(item => ({
				id: item.id,
				url: `${config.static_URL}${item.imgPath}`
			})) : []
			allAdv2.value = (aRes.code === 200 && Array.isArray(aRes.objData?.[2])) ? aRes.objData[2].map(item =>
		({
				id: item.id,
				url: `${config.static_URL}${item.imgPath}`
			})) : []
		} else {
			const res = await $API.backend.businessStation.getStationImgs.post({
				id: formState.value.id,
				type
			})
			const list = (res.code === 200 && Array.isArray(res.objData?.[type])) ? res.objData[type].map(item =>
		({
				id: item.id,
				url: `${config.static_URL}${item.imgPath}`
			})) : []
			type === 1 ? (allAdv.value = list) : (allAdv2.value = list)
		}
	}
	const onReset = () => {
		allAdv.value = []
		allAdv2.value = []
		formState.value = {
			id: '',
			orgId: null,
		}
	}

	const onClose = () => {
		onReset()
		visible.value = false
		emit('close')
	}

	const add = () => {
		mode.value = 'add'
		title.value = $T('self.businessStation.modal.col1')
		visible.value = true
	}

	const edit = (record) => {
		formState.value.id = record.id
		title.value = $T('self.businessStation.title')
		visible.value = true
		getPileAdv();
	}

	defineExpose({
		add,
		edit,
	})
</script>

<style lang="scss" scoped>
	.edit-drawer {
		position: relative;

		.closeable {
			@include closeable;
		}
	}

	.my-upload {
		::v-deep(.ant-upload) {
			width: 100px;
			height: 100px;
		}
	}

	.adv-list {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		margin-top: 10px;
	}

	.adv-item {
		width: 100px;
		text-align: center;
		// border: 1px solid #ccc;
		padding-top: 5px;
		height: 100px;
		position: relative;
	}

	.pic-box img {
		width: 100px;
		height: 100px;
		object-fit: cover;
	}

	.del-box {
		position: absolute;
		right: 0px;
		top: 0px;
	}

	.del-box img {
		width: 20px;
		height: 20px;
		cursor: pointer;
		margin: 4px 0;
	}

	.upload-line {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.upload-tip {
		font-size: 12px;
		color: #999;

		.count {
			margin-left: 8px;
			color: #faad14;
		}
	}
</style>